<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 3/28/17
 * Time: 5:00 PM
 */

namespace common\models;


use common\components\gps\Api;
use common\components\gps\BeiDou;
use common\components\gps\BeiDou1;
use common\components\gps\Exlive;
use common\components\gps\Haode;
use common\components\gps\Jimi;
use common\components\gps\JinLiMing;
use common\components\gps\Sunmu;
use wodrow\yii\rest\ApiException;
use yii\base\ErrorException;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;

/**
 * Class CarGpsOrder
 * @package common\models
 *
 * @property User $createdBy
 * @property User $updatedBy
 * @property GuaranteeCompany $guaranteeCompany
 * @property CarGpsOrderStatusUpdateLog[] $carGpsOrderStatusUpdateLogs
 */
class CarGpsOrder extends \common\models\base\CarGpsOrder
{
    const STATUS_NOT_ADD = 10; // 未安装
    const STATUS_ADDING = 11; // 安装中
    const STATUS_HAS_ADD = 12; // 已安装
    const STATUS_ONLINE = 13; // 已上线/在线
    const STATUS_ALARM = 14; // 报警
    const STATUS_OFFLINE = 15; // 已下线/离线

    public $other_data;

    public static function getStatus()
    {
        return [
            self::STATUS_NOT_ADD => '未安装',
            self::STATUS_ADDING => '安装中',
            self::STATUS_HAS_ADD => '已安装',
            self::STATUS_ONLINE => '已上线/在线',
            self::STATUS_ALARM => '报警',
            self::STATUS_OFFLINE => '已下线/离线',
        ];
    }

    /**
     * @param $gps_serial_number
     * @return Api
     * @throws
     */
    public static function getPlatForm($gps_serial_number)
    {
        $pre_sign = substr($gps_serial_number, 0, 3);
        switch ($pre_sign) {
            case Sunmu::PRE_SIGN:
                $platform = new Sunmu();
                break;
            case '039':
                $platform = new Sunmu();
                break;
            case '391':
                $platform = new Sunmu();
                break;
            case '135':
                if (substr($gps_serial_number, 0, 4) == '1358'){
                    $platform = new Sunmu();
                }else{
                    throw new ApiException(201905311135, '没有找到gps平台');
                }
                break;
            case Jimi::PRE_SIGN;
//                throw new ApiException(201908261620, "几米已停用");
                $platform = new Jimi();
                break;
            case Haode::PRE_SIGN;
                $platform = new Haode();
                break;
            case Exlive::PRE_SIGN;
                $platform = new Exlive();
                break;
            case JinLiMing::PRE_SIGN;
//                throw new ApiException(201908261619, "金立铭已停用");
                $platform = new JinLiMing();
                break;
            case BeiDou1::PRE_SIGN:
                $platform = new BeiDou1();
                break;
            case '141':
                $platform = new BeiDou1();
                break;
            default:
//                \Yii::$app->response->statusCode = 401;
//                exit;
                throw new ErrorException('没有找到gps平台');
                break;
        }
        return $platform;
    }

    public static function getGps($gps_serial_number, $is_direct, $other_data)
    {
        $plat = self::getPlatForm($gps_serial_number);
        if ($is_direct){
            $plat->order = new self();
            $plat->order->gps_serial_number = $gps_serial_number;
        }else{
            $plat->order = self::findOne(['gps_serial_number'=>$gps_serial_number]);
            if (!$plat->order&&in_array($plat::PRE_SIGN, [Exlive::PRE_SIGN])){
                $plat->order = new self();
                $plat->order->gps_serial_number = $gps_serial_number;
            }
        }
        $plat->order->other_data = $other_data;
        return $plat->getGps();
    }

    public static function alarm($gps_serial_number)
    {
        $order = self::findOne(['gps_serial_number'=>$gps_serial_number]);
        $old_status = $order->status;
        $order->status = self::STATUS_ALARM;
        if ($old_status!=$order->status){
            $order->save();
        }
        $arr = $order->toArray();
        $arr['status'] = $arr['status'].":".$order::getStatus()[$arr['status']];
        return $arr;
    }

    public function behaviors()
    {
        return [
            [
                'class' => BlameableBehavior::className(),
                'updatedByAttribute' => false,
            ],
            [
                'class' => TimestampBehavior::className(),
            ]
        ];
    }

    public function rules()
    {
        return [
            [['guarantee_company_car_id', 'guarantee_company_id', 'gps_serial_number', 'status'], 'required'],
            [['guarantee_company_car_id', 'guarantee_company_id', 'status', 'created_at', 'created_by', 'updated_at', 'updated_by'], 'integer'],
            [['data'], 'string'],
            [['gps_serial_number'], 'string', 'max' => 50],
            [['gps_serial_number'], 'unique'],
            [['guarantee_company_car_id', 'guarantee_company_id'], 'unique', 'targetAttribute' => ['guarantee_company_car_id', 'guarantee_company_id'], 'message' => 'The combination of Guarantee Company Car ID and Guarantee Company ID has already been taken.'],
            [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['created_by' => 'id']],
            [['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['updated_by' => 'id']],
            [['guarantee_company_id'], 'exist', 'skipOnError' => true, 'targetClass' => GuaranteeCompany::className(), 'targetAttribute' => ['guarantee_company_id' => 'id']],
            ['data', 'safe'],
        ];
    }

    /*public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        // 平台添加
        if ($insert) {
            $plat = self::getPlatForm(substr($this->gps_serial_number, 0, 3));
            $plat->order = $this;
            $plat->addGps();
        }
        // 添加日志
        $log = New CarGpsOrderStatusUpdateLog();
        $log->order_id = $this->id;
        $log->time = time();
        $log->old_status = $insert ? 0 : $changedAttributes['status'];
        $log->new_status = $this->status;
        $log->order_data = serialize($this->toArray());
        if (!$log->save()) {
            throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
        }
    }*/

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'created_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUpdatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'updated_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGuaranteeCompany()
    {
        return $this->hasOne(GuaranteeCompany::className(), ['id' => 'guarantee_company_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCarGpsOrderStatusUpdateLogs()
    {
        return $this->hasMany(CarGpsOrderStatusUpdateLog::className(), ['order_id' => 'id']);
    }
}